﻿using Learun.Application.Base.SystemModule;
using Learun.Application.Organization;
using Learun.Util;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using static Learun.Application.TwoDevelopment.ZZDT_EC.ProjectSugar;
using static Learun.Util.SqlSugar.SqlSugarHelper;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-02-23 11:30
    /// 描 述：属性表
    /// </summary>
    public class ec_propertyBLL : ec_propertyIBLL
    {
        private ec_propertyService ec_propertyService = new ec_propertyService();

        #region 获取数据
        /// <summary>
        /// 获取页面显示列表数据
        /// <summary>
        /// <param name="queryJson">查询参数</param>
        /// <returns></returns>
        public IEnumerable<ec_propertyEntity> GetList(string queryJson, string engineDataID = "", string caseID = "", Pagination pagination = null)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                var ProjectId = queryParam["ProjectId"]?.ToString();
                var PropertyIDs = queryParam["PropertyIDs"]?.ToString();
                var PropertyName = queryParam["PropertyName"]?.ToString();
                var PropertyGID = queryParam["PropertyGID"]?.ToString();
                var ObjectTypeID = queryParam["ObjectTypeID"]?.ToString();
                
                var tableName = TableName<ec_propertyEntity>(ProjectId);
                var pTableName = TableName<ec_objecttypepEntity>(ProjectId);
                var dataTableName = TableName<ec_enginedataEntity>(ProjectId);

                var query = Db.Queryable<ec_propertyEntity>().AS(tableName)
                    .WhereIF(!string.IsNullOrEmpty(PropertyIDs), x => SqlFunc.SplitIn(PropertyIDs, x.PropertyID))
                    .WhereIF(!string.IsNullOrEmpty(PropertyName), x => x.PropertyName == PropertyName)
                    .WhereIF(!string.IsNullOrEmpty(PropertyGID), x => x.PropertyGID == PropertyGID)
                    .WhereIF(!string.IsNullOrEmpty(ObjectTypeID), x => x.PropertyID == SqlFunc.Subqueryable<ec_objecttypepEntity>().AS(pTableName)
                        .Where(y => y.ObjectTypeID == ObjectTypeID).GroupBy(y => y.PropertyID).Select(y => y.PropertyID))
                    .OrderByDescending(x => x.CreateTime);
                List<ec_propertyEntity> list;
                if (pagination == null)
                {
                    list = query.ToList();
                }
                else
                {
                    list = query.ToPageList(pagination.page, pagination.rows);
                }
                if (!string.IsNullOrEmpty(engineDataID))
                {
                    var datas = Db.Queryable<ec_enginedataEntity>().AS(dataTableName).Where(x => x.EngineDataID == engineDataID && x.CaseID == caseID).ToList();
                    
                }
                var users = Db.Queryable<UserEntity>().ToList();
                var details = Db.Queryable<DataItemDetailEntity>()
                    .InnerJoin<DataItemEntity>((a, b) => a.F_ItemId == b.F_ItemId && b.F_ItemCode == "Be_DataType").ToList();
                var itemTableName = TableName<ec_dataitemEntity>(ProjectId);
                var typeTableName = TableName<ec_measuring_unittypeEntity>(ProjectId);
                var unitTableName = TableName<ec_measuring_unitEntity>(ProjectId);
                var itemCodes = list.Select(x => x.EnumData).ToList();
                var typeIds = list.Select(x => x.MeasuringUnitTypeID).ToList();
                var unitIds = list.Select(x => x.DefaultUnit).ToList();
                var items = Db.Queryable<ec_dataitemEntity>().AS(itemTableName).Where(x => itemCodes.Contains(x.DataItemCode)).ToList();
                var types = Db.Queryable<ec_measuring_unittypeEntity>().AS(typeTableName).Where(x => typeIds.Contains(x.MeasuringUnitTypeID)).ToList();
                var units = Db.Queryable<ec_measuring_unitEntity>().AS(unitTableName).Where(x => unitIds.Contains(x.MeasuringUnitID)).ToList();
                list?.ForEach(x =>
                {
                    x.EngineCreateUserName = users.FirstOrDefault(y => y.F_UserId == x.CreateUserID)?.F_RealName;
                    x.EngineUpdateUserName = users.FirstOrDefault(y => y.F_UserId == x.UpdateUserID)?.F_RealName;
                    x.PropertyTypeName = details.FirstOrDefault(y => y.F_ItemValue == x.PropertyType)?.F_ItemName;
                    x.EnumDataName = items.FirstOrDefault(y => y.DataItemCode == x.EnumData)?.DataItemName;
                    x.MeasuringUnitTypeName = types.FirstOrDefault(y => y.MeasuringUnitTypeID == x.MeasuringUnitTypeID)?.MeasuringUnitTypeName;
                    x.MeasuringUnitName = units.FirstOrDefault(y => y.MeasuringUnitID == x.DefaultUnit)?.MeasuringUnitName;
                });
                if (!string.IsNullOrEmpty(engineDataID))
                {
                    var propertyTableName = TableName<ec_enginedata_propertyEntity>(ProjectId);
                    var propertys = Db.Queryable<ec_enginedata_propertyEntity>().AS(propertyTableName).Where(x => x.EngineDataID == engineDataID && x.CaseID == caseID).ToList();
                    list?.ForEach(x =>
                    {
                        var property = propertys.First(y => y.PropertyName == x.PropertyName);
                        if (property != null)
                        {
                            x.PropertyValue = property.PropertyValue;
                            x.EngineCreateTime = property.CreateTime;
                            x.EngineUpdateTime = property.UpdateTime;
                            x.EngineDataPropertyID = property.EngineDataPropertyID;
                            x.MeasuringUnitName = property.MeasuringUnit;
                        }
                    });
                }
                var dataItemDetailIds = list.Where(x => x.PropertyType == "00003").Select(x => x.DefaultValue).Distinct().ToList();
                var detailTableName = TableName<ec_dataitemdetailEntity>(queryParam["ProjectId"].ToString());
                var dataItemDetails = Db.Queryable<ec_dataitemdetailEntity>().AS(detailTableName).Where(x => dataItemDetailIds.Contains(x.DataItemDetailID)).ToList();
                list.Where(x => x.PropertyType == "00003").ToList().ForEach(x =>
                {
                    var item = dataItemDetails.FirstOrDefault(y => y.DataItemDetailID == x.DefaultValue);
                    if (item != null)
                    {
                        x.DefaultValue = item.DataItemName;
                    }
                });
                return list;
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 获取实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public ec_propertyEntity GetEntity(string keyValue, string ProjectId)
        {
            try
            {
                return ec_propertyService.GetEntity(keyValue, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 获取左侧树形数据
        /// <summary>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        public List<TreeModel> GetTree(string ProjectId)
        {
            try
            {
                DataTable list = ec_propertyService.GetSqlTree(ProjectId);
                List<TreeModel> treeList = new List<TreeModel>();
                foreach (DataRow item in list.Rows)
                {
                    TreeModel node = new TreeModel
                    {
                        id = item["propertygid"].ToString(),
                        text = item["propertygroupname"].ToString(),
                        value = item["propertygid"].ToString(),
                        showcheck = false,
                        checkstate = 0,
                        isexpand = true,
                        parentId = ""
                    };
                    treeList.Add(node);
                }
                return treeList.ToTree();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 命名规则时用到
        /// yxh
        /// 2022 08 28
        /// <summary>
        ///<param name="ProjectId">项目ID</param>
        /// <returns></returns>
        public List<TreeModel> GetPropTreeDataByType(string ProjectId, string ObjectTypeId, bool isShowCheck)
        {
            try
            {
                var listProp = new ec_objecttypepService().GetObjectTypePById(ObjectTypeId, ProjectId, true).ToList();

                //根据属性组分组
                var listPropGroup = listProp.GroupBy(x => new { x.PropertyGID, x.PropertyGroupName }).ToList();
                List<TreeModel> treeList = new List<TreeModel>();
                foreach (var parent in listPropGroup)
                {
                    TreeModel node = new TreeModel
                    {
                        id = parent.Key.PropertyGID,
                        text = parent.Key.PropertyGroupName,
                        value = parent.Key.PropertyGID,
                        checkstate = 0,
                        showcheck = isShowCheck,
                        isexpand = true,
                        parentId = "",
                        nodeType = "0"
                    };
                    treeList.Add(node);
                }
                foreach (var child in listProp)
                {
                    TreeModel node = new TreeModel
                    {
                        id = child.PropertyID,
                        text = child.PropertyName,
                        value = child.PropertyID,
                        checkstate = 0,
                        showcheck = isShowCheck,
                        isexpand = false,
                        parentId = child.PropertyGID,
                        nodeType = "1"
                    };
                    treeList.Add(node);
                }
                return treeList.ToTree();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 获取属性树形数据（TreeModel,第一级为属性组，第二级为属性）
        /// <summary>
        ///<param name="ProjectId">项目ID</param>
        /// <returns></returns>
        public List<TreeModel> GetPropTreeData(string ProjectId, bool isShowCheck)
        {
            try
            {
                var listProp = ec_propertyService.GetSqlPropTree(ProjectId).ToList();
                //根据属性组分组
                var listPropGroup = listProp.GroupBy(x => new { x.PropertyGID, x.PropertyGroupName }).ToList();
                List<TreeModel> treeList = new List<TreeModel>();
                foreach (var parent in listPropGroup)
                {
                    TreeModel node = new TreeModel
                    {
                        id = parent.Key.PropertyGID,
                        text = parent.Key.PropertyGroupName,
                        value = parent.Key.PropertyGID,
                        checkstate = 0,
                        showcheck = isShowCheck,
                        isexpand = false,
                        parentId = "",
                        nodeType = "0"
                    };
                    treeList.Add(node);
                }
                foreach (var child in listProp)
                {
                    TreeModel node = new TreeModel
                    {
                        id = child.PropertyID,
                        text = child.PropertyName,
                        title = child.PropertyNameEN,
                        value = child.PropertyID,
                        checkstate = 0,
                        showcheck = isShowCheck,
                        isexpand = false,
                        parentId = child.PropertyGID,
                        nodeType = "1"
                    };
                    treeList.Add(node);
                }
                return treeList.ToTree();
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion

        #region 提交数据

        /// <summary>
        /// 删除实体数据
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void DeleteEntity(string keyValue, string ProjectId)
        {
            try
            {
                ec_propertyService.DeleteEntity(keyValue, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_propertyEntity entity, string ProjectId)
        {
            try
            {
                ec_propertyService.SaveEntity(keyValue, entity, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        #endregion

    }
}
